<?php

namespace app\api\controller\shop;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\ErrorException;
use think\Config;


/**
 * 服务商B端小程序接口
 */
class Bshop extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

   
     /**
     * 服务商首页
     * 
     * 
     *  
     */
    public function shopindex()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
    	$stime = $this->request->request('stime'); //开始时间
        $etime = $this->request->request('etime'); //结束时间 
      
        $where['id'] = $this->auth->service_id;
      
		$list = Db::name('wanlshop_service')
			->where($where)
			->find();
            
        
        $map['service_id'] = $this->auth->service_id;
        if($stime && $etime)
        {
            $map['createtime'][] = ['>=', $stime];
            $map['createtime'][] = ['<=', $etime];
        }
        $list['rebate_sum'] =   Db::name('shop_rebate')
        //->where('service_id','=',$this->auth->service_id)
        //->whereTime('createtime','month')
        ->where($map)
        ->sum('amount'); 

        $map['status'] = 1;
        $list['m_r_sum'] =  Db::name('shop_rebate')
        //->where('service_id','=',$this->auth->service_id)
        //->where('status','=',1)
        //->whereTime('createtime','month')
        ->where($map)
        ->sum('amount'); 
        $map['status'] = 0;
        $list['m_r_pay'] =  Db::name('shop_rebate')
        //->where('service_id','=',$this->auth->service_id)
        //->where('status','=',0)
        //->whereTime('createtime','month')
        ->where($map)
        ->sum('amount'); 

        //$where[] = ['exp', Db::raw("FIND_IN_SET($id,e.shop_ids)")];
       $map2['s.id'] = $this->auth->service_id;
       if($stime && $etime)
       {
           $map2['r.createtime'][] = ['>=', $stime];
           $map2['r.createtime'][] = ['<=', $etime];
       }
       $data = Db::name('wanlshop_service') ->alias('s')
              ->field('count(distinct o.shop_id) as ssum,count( distinct o.id) as osum')
              ->join('wanlshop_shop sh','FIND_IN_SET(sh.id, s.shop_ids) > 0','left')
              ->join('shop_rebate r','r.service_id=s.id','left')
              ->join('wanlshop_order o','o.id = r.order_id','left')
              //->where('s.id','=',$this->auth->service_id)
              //->whereTime('r.createtime','month')
              ->where($map2)
              ->select();
             

        $list['m_shop'] = $data[0]['ssum'] ;

        $list['m_number'] =  $data[0]['osum'] ;

        $map3['r.service_id'] = $this->auth->service_id;
        if($stime && $etime)
        {
            $map3['r.createtime'][] = ['>=', $stime];
            $map3['r.createtime'][] = ['<=', $etime];
        }
        $data1 = Db::name('shop_rebate') ->alias('r')
        ->field('sum(o.actual_price) as sum')
        ->join('wanlshop_order o','o.id = r.order_id','left')
        //->where('r.service_id','=',$this->auth->service_id)
        //->whereTime('r.createtime','month')
        ->where($map3)
        ->select();

        $list['y_refund'] =  '0.00' ;
        $list['y_pay'] =  $data1[0]['sum'] ;

        $data2 = Db::name('wanlshop_service') ->alias('s')
        ->field('count(sh.id) as ssum,sum( case when sh.createtime >UNIX_TIMESTAMP(DATE_FORMAT(CURDATE(), "%Y-%m-01")) then 1 else 0 end) as osum')
        ->join('wanlshop_shop sh','FIND_IN_SET(sh.id, s.shop_ids) > 0','left') 
        ->where('s.id','=',$this->auth->service_id)
       
        ->select();

        $list['shop_sum'] =  $data2[0]['ssum'] ;
        $list['shop_add'] =  $data2[0]['osum'] ;
        $list['shop_wait'] =  0 ;
        $list['firstloan'] = 5000.00 ;//贷款金额

        $list['pay_1'] = Db::name('shop_rebate')
        ->where('service_id','=',$this->auth->service_id)
        ->where('status','=',0)
        ->sum('amount'); 
        $list['pay_2'] = Db::name('lal_member_withdraw')
        ->where('shop_id','=',$this->auth->service_id)
        ->where('type','=',1)
        ->where('status','=',0)
        ->sum('amount'); 
        $list['pay_3'] = Db::name('shop_rebate')
        ->where('service_id','=',$this->auth->service_id)
        ->where('status','=',1)
        ->sum('amount'); 
        $list['pay_4'] =  Db::name('shop_rebate')
        ->where('service_id','=',$this->auth->service_id)
        ->where('status','=',0)
        ->sum('amount'); 
		$list['pay_img'] = Config::get('site.corporate_payment');
        $this->success('ok', $list);
	
    }


   
     /**
     * 门店列表
     * 
     * 
     *  @param string $keyword  店铺名称
     */
    public function shoplist()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
    	$keyword = $this->request->request('keyword'); 
      
        if (!in_array($this->auth->wxmanage, [1,2])) {
            $this->error(__('非法请求'));
        }

        if ($keyword) {
        	$where['sh.shopname'] = ['like', '%'.$keyword.'%'];   
        }
        $where['sh.status'] = 'normal';

        if ($this->auth->wxmanage == 1 && $this->auth->shop_id != 1) {
            $where['sh.user_id'] = $this->auth->id;
        }

        if ($this->auth->wxmanage == 2) {
            $where['s.id'] = $this->auth->service_id;
            $list = Db::name('wanlshop_service') ->alias('s')
                ->join('wanlshop_shop sh','FIND_IN_SET(sh.id, s.shop_ids) > 0','left') 
                ->field('distinct(sh.id),sh.shopname,sh.city,sh.type,sh.status,sh.avatar')
                // ->where('s.id','=',$this->auth->service_id)
                ->where($where)
                ->paginate();
            $this->success('ok', $list);
        }

        $list = Db::name('wanlshop_shop') ->alias('sh')
                ->field('sh.id,sh.shopname,sh.city,sh.type,sh.status,sh.avatar')
                // ->where('s.id','=',$this->auth->service_id)
                ->where($where)
                ->paginate();
        $this->success('ok', $list);
	
    }

     /**
     * 服务返利列表
     * 
     *  @param int $stime  开始时间
     *  @param int $etime  结束时间
     *  @param int $shop_id  店铺ID
     *  @param int $state  状态
     */
    public function respay()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
    	$stime = $this->request->request('stime'); 
        $etime = $this->request->request('etime'); 
        $shop_id = $this->request->request('shop_id'); 
        $state = $this->request->request('state'); 
        $where1 =[];
        if ($stime) {
        $where['o.createtime'] = ['>=', $stime]; 
        $where1['o.createtime'] = ['<=', $etime];   
        } 

       
        if ($shop_id) {
        	$where['o.shop_id'] = $shop_id;   
        }
        if ($state) {
        	$where['o.state'] = $state;   
        }   
        $where['o.status'] = 'normal';
        //$where['s.staff_id'] = $this->auth->staff_id;
		
		$list = Db::name('wanlshop_order o')
            ->join('wanlshop_shop s', 's.id = o.shop_id', 'left')
			->where($where)
            ->where($where1)
			->field('o.id,o.order_no,o.createtime,o.actual_price,"200" as number,  o.actual_price  as respay,o.state ,s.shopname')
			->order('o.id desc')
			->paginate();
		
        $this->success('ok', $list);
	
    }


    /**
     * 门店订单详情
     * 
     * @param int $id  订单id
     *  
     */
    public function orderinfo()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
    	 $order_id = $this->request->request('id'); 
        // $time = date("Y-m", $keyword);
       
        // $time =  strtotime($time);
        // $endtime = strtotime("+1 month", $keyword);
        // $endtime = date("Y-m", $endtime);
       
        // $endtime = strtotime($endtime);
       
        //  if ($keyword) {
        //  	$where['clocktime'] = ['between time', [$time, $endtime]];      
        //  }
       
        $where['o.id'] = $order_id;
        // $where['s.gdtype'] = 0;
		
		$list = Db::name('wanlshop_order o')
            //->join('wanlshop_order_goods s', 's.order_id = o.id', 'inner')
            ->join('wanlshop_shop p', 'p.id = o.shop_id', 'left')
			->where($where)
			->field('o.id,o.order_no,o.createtime,o.delivertime,o.actual_price,p.shopname')
			->find();
       $list['info'] =  Db::name('wanlshop_order_goods')
       ->where('order_id','=',$order_id )
       ->field('id,title,number,actual_payment,difference')
       ->select();  

        $this->success('ok', $list);
	
    }

     /**
     * 全部门店列表/订货明细
     * 
     *  @param int $stime  开始时间
     *  @param int $etime  结束时间
     *  @param string $keyword  店铺名称
     *  @param int $shop_id  店铺ID
     */
    public function allorderlist()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
    	$stime = $this->request->request('stime'); 
        $etime = $this->request->request('etime'); 
        $keyword = $this->request->request('keyword');
        $shop_id = $this->request->request('shop_id');
        $key_type = $this->request->request('key_type');
        $where1 =[];
        if ($stime) {
            $where['o.createtime'] = ['>=', $stime]; 
            $where1['o.createtime'] = ['<=', $etime];   
        }  
        if ($keyword) {
        	switch($key_type)
            {
                //手机号
                case 'mobile':
                    //echo '手机号';
                    //查询收货人的手机号
                    $address_id_arr1 = Db::name('wanlshop_address')->where(['mobile' => ['like', '%'.$keyword.'%']])->column('id');
                    $address_id_arr2 = Db::name('wanlshop_shop_address')->where(['mobile' => ['like', '%'.$keyword.'%']])->column('id');
                    $address_idarr = array_merge($address_id_arr1, $address_id_arr2);
                    if(!empty($address_idarr))
                    {
                        $address_idarr = array_values(array_unique($address_idarr));
                    }else
                    {
                        $address_idarr = [-1];
                    }
                    $where['o.address_id'] = ['in', $address_idarr];
                break;
                //收货人
                case 'address_name':
                    //echo '收货人';
                    //查询收货人的姓名
                    $address_id_arr1 = Db::name('wanlshop_address')->where(['name' => ['like', '%'.$keyword.'%']])->column('id');
                    $address_id_arr2 = Db::name('wanlshop_shop_address')->where(['name' => ['like', '%'.$keyword.'%']])->column('id');
                    $address_idarr = array_merge($address_id_arr1, $address_id_arr2);
                    if(!empty($address_idarr))
                    {
                        $address_idarr = array_values(array_unique($address_idarr));
                    }else
                    {
                        $address_idarr = [-1];
                    }
                    $where['o.address_id'] = ['in', $address_idarr];
                break;
                //订单编号
                case 'order_no':
                    //echo '订单编号';
                    $where['o.order_no'] = $keyword;
                break;
                //店铺
                case 'shopname':
                    //echo '店铺';
                    $where['p.shopname'] = ['like', '%'.$keyword.'%'];
                break;
            }   
        }
        if ($shop_id) {
            // $where['p.id'] = $shop_id;  
            $where['o.b_shop_id'] = $shop_id;  
        }else{
            if($this->auth->wxmanage == 2)
            {
                $wanlshop_service_info = Db::name('wanlshop_service')->where(['id' => $this->auth->service_id])->find();
                if(!empty($wanlshop_service_info['shop_ids']))
                {
                    $where['o.b_shop_id'] = ['in', $wanlshop_service_info['shop_ids']];
                }else
                {
                    $where['o.b_shop_id'] = ['in', '-1'];
                }
            }
        }

        $where['o.status'] = 'normal';
        $where['o.data_type'] = 'merchant';
        //$where['s.staff_id'] = $this->auth->staff_id;
		

		$list = Db::name('wanlshop_order o')
            //->join('wanlshop_order_goods s', 's.order_id = o.id', 'inner')
            ->join('wanlshop_shop p', 'p.id = o.shop_id', 'left')
			->where($where)
            ->where($where1)
			->field('o.id, o.user_id, o.address_id, o.paymenttime, o.order_no, o.state as order_state, o.createtime,o.delivertime,o.actual_price,p.shopname')
			->order('o.createtime desc')
			->paginate();

            foreach ($list as $k => $row) {
               // $row->shop->visible(['state','shopname']);
               $row['info'] = Db::name('wanlshop_order_goods')
                ->where('order_id','=',$row['id'] )
                ->field('id,title,number,actual_payment,difference')
                ->select();
                
                //查询用户信息
                $row['user_info'] = Db::name('user')->where(['id' => $row['user_id']])->find();
                //查询店铺收货地址
                $row['shop_address'] = Db::name('wanlshop_shop_address')->where(['id' => $row['address_id']])->find();

                $list[$k] = $row;

            }
          
            
        $this->success('ok', $list);
	
    }


     /**
     * 门店详情
     * 
     * @param int $shop_id  店铺ID
     *  
     */
    public function shopinfo()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
    	$shop_id = $this->request->request('shop_id'); 
        $stime = $this->request->request('stime'); //开始时间
        $etime = $this->request->request('etime'); //结束时间 
        $where['id'] = $shop_id;
       

		$list = Db::name('wanlshop_shop')
			->where($where)
			->find();
        


        
        //本月
        $map['o.shop_id'] = $shop_id;
        if($stime && $etime)
        {
            $map['o.createtime'][] = ['>=', $stime];
            $map['o.createtime'][] = ['<=', $etime];
        }
        $map['o.state'] = ['in', ['2,3,4,5,6']];
        $list['sum'] =  Db::name('wanlshop_order') ->alias('o')
        //->join('wanlshop_order_goods g','o.id=g.order_id','left') 
        //->where('o.shop_id','=',$shop_id)
        //->whereTime('o.createtime','month')
        //->where('o.state','in','2,3,4,5,6')
        ->where($map)
        ->sum('o.actual_price'); 

        $list['t_sum_0'] = Db::name('wanlshop_order') ->alias('o')
        ->join('wanlshop_order_goods g','o.id=g.order_id','left') 
        //->where('o.shop_id','=',$shop_id)
        //->whereTime('o.createtime','month')
        //->where('o.state','in','2,3,4,5,6')
        ->where($map)
        ->sum('g.actual_payment'); 

        $list['t_sum_1'] =  95841.00 ;
        $list['t_sum_2'] =  94541.00 ;
        //上月
        $list['y_sum_0'] =  200000.00 ;
        $list['y_sum_1'] =  95841.00 ;
        $list['y_sum_2'] =  94541.00 ; 
       //本月订货数据
        $map2['r.service_id'] = $this->auth->service_id;
        $map2['o.shop_id'] = $shop_id;
        if($stime && $etime)
        {
            $map2['o.createtime'][] = ['>=', $stime];
            $map2['o.createtime'][] = ['<=', $etime];
        }
        $list['m_number'] =  Db::name('shop_rebate') ->alias('r')
        ->join('wanlshop_order_goods o','o.order_id=r.order_id','left')
        //->where('r.service_id','=',$this->auth->service_id)
        //->where('o.shop_id','=',$shop_id)
        //->whereTime('o.createtime','month')
        ->where($map2)
        ->sum('o.number');  
        $list['y_refund'] =   Db::name('shop_rebate') ->alias('r')
        ->join('wanlshop_order o','o.id=r.order_id','left')
        //->where('r.service_id','=',$this->auth->service_id)
        //->where('o.shop_id','=',$shop_id)
        //->whereTime('o.createtime','month')
        ->where($map2)
        ->count();
        $list['y_pay'] =  Db::name('shop_rebate') ->alias('r')
        ->join('wanlshop_order o','o.id=r.order_id','left')
        //->where('r.service_id','=',$this->auth->service_id)
        //->where('o.shop_id','=',$shop_id)
        //->whereTime('o.createtime','month')
        ->where($map2)
        ->sum('o.actual_price');

        $list['address_id'] = 0;
        $addressinfo = Db::name('wanlshop_shop_address')->field('id,name,mobile,address')->where(['shop_id'=>$shop_id,'default'=>1])->find();
        if(!empty($addressinfo)){
            $list['address_id'] = $addressinfo['id']; 
        }

        $list['address_info'] =  $addressinfo; //订货地址

        // $list['address_id'] =  1 ; //订货地址
		
        $this->success('ok', $list);
	
    }


     /**
     * 财务概况
     * 
     *  @param int $state  状态1待结算2已结算
     *  
     *  
     */
    public function res()
    {
        //设置过滤方法
		$this->request->filter(['strip_tags']);
    	$state = $this->request->request('state'); 
        
        if ($state) {
        $where['o.state'] = $state ;  
        }    
        $where['o.status'] = 'normal';
        //$where['s.staff_id'] = $this->auth->staff_id;
		
		$list = Db::name('wanlshop_order o')
            ->join('wanlshop_shop s', 's.id = o.shop_id', 'left')
			->where($where)
			->field('o.id,o.order_no,o.createtime,o.actual_price,"200" as number,  o.actual_price  as respay,o.state ,s.shopname')
			->order('s.updatetime desc')
			->paginate();
        
    
        
		
        $this->success('ok', $list);
	
    }

    /**
     * 打款明细
     * 
     * 
     *  @param string $keyword  时间
     */
    public function cashlist()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $keyword = $this->request->request('keyword');
        $time = date("Y-m", $keyword);

        $time = strtotime($time);
        $endtime = strtotime("+1 month", $keyword);
        $endtime = date("Y-m", $endtime);

        $endtime = strtotime($endtime);

        if ($keyword) {
            $where['createtime'] = ['between time', [$time, $endtime]];
        }

        $where['shop_id'] = $this->auth->shop_id;

        $list = Db::name('lal_member_withdraw')
            ->where($where)
            //->field('s.id,s.starttime,s.endtime,s.scheduletime,c.code,c.name')
            ->order('createtime desc')
            ->paginate();

        $this->success('ok', $list);

    }

    /**
     * 申请提现
     * 
     *  @param string $keyword  提现金额
     *  
     *  
     */
    public function withdraw()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $keyword = $this->request->request('keyword');
        $shop = $this->auth->service_id;
        $date = [
            'code' => time(),
            'type' => 1,
            'shop_id' => $shop,
            'name' => '',
            'amount' => $keyword,
            'createtime' => time()
        ];
        $list = Db::name('lal_member_withdraw')->insert($date);
        $this->success('ok', $list);
    }

    /**
     * 获取地址列表
     * 
     */
    public function getaddress()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $list = model('app\admin\model\store\Shopaddress')
            ->where('shop_id', $this->shop_id)
            ->field('id,name,mobile,default,province,city,area,formatted_address,address,status')
            ->order('updatetime desc')
            ->paginate();
        $this->success('返回成功', $list);
    }

    /**
     * 修改/新增地址
     * 
     * @param string $shop_id
     */
    public function editaddress()
    {
        if ($this->request->isPost()) {
            //设置过滤方法
            $this->request->filter(['strip_tags']);
            $request = $this->request->post();
            $address = new \app\admin\model\store\Shopaddress();
            $data = $request['data'];
            $data['shop_id'] = $this->shop_id;
            $count = $address->where(['shop_id'=>$data['shop_id']])->count();
            // 操作           
            switch ($request['type']) {
                case "edit": 
                    if($count <= 1){
                        $data['default'] = 1;
                        $address->allowField(true)->save($data,['id' => $data['id']]);
                        $this->success('ok','成功(仅一个不许修改默认)');
                    }else{
                        // 更新
                        $address->allowField(true)->save($data,['id' => $data['id']]);
                        // 单独设置默认，避免非默认消耗资源
                        if($data['default'] == 1){
                            $list = \app\admin\model\store\Shopaddress::all(['shop_id'=>$data['shop_id']]);
                            $list = collection($list)->toArray();
                            $itemdata = [];
                            foreach($list as $item){
                                if($item['id'] == $data['id']){
                                    $item['default'] = 1;
                                }else{
                                    $item['default'] = 0;
                                }
                                $itemdata[] = $item;
                            }
                            $address->allowField(true)->saveAll($itemdata);
                        }
                        $this->success('ok');
                    }
                    break;
                case "add": 
                    if($count == 0){
                        // 新增
                        $data['default'] = 1;
                        $address->data($data);
                        $address->allowField(true)->save(); // 1.1.5升级
                        $this->success('地址回调',$address);
                    }else{
                        $address->data($data);
                        $address->allowField(true)->save(); // 1.1.5升级
                        if($data['default'] == 1){
                            $list = \app\admin\model\store\Shopaddress::all(['shop_id'=>$data['shop_id']]);
                            $list = collection($list)->toArray();
                            $itemdata = [];
                            foreach($list as $item){
                                if($item['id'] == $address->id){
                                    $item['default'] = 1;
                                }else{
                                    $item['default'] = 0;
                                }
                                $itemdata[] = $item;
                            }
                            $address->saveAll($itemdata);
                        }
                        $this->success('新增成功',[]);      
                    }
                    break;
            }
        } else {
            $this->error(__('非法请求'));
        }
    }
    
    /**
     * 删除地址
     *
     * @ApiSummary  (WanlShop 地址接口删除地址)
     * @ApiMethod   (POST)
     * 
     * @param string $id 地址ID
     */
    public function deladdress()
    {
        if ($this->request->isPost()) {
            //设置过滤方法
            $this->request->filter(['strip_tags']);
            $id = $this->request->post('id');
            if (!$id) {
                $this->error(__('Invalid parameters'));
            }
            if(model('app\admin\model\store\Shopaddress')->where(['id'=>$id,'shop_id'=>$this->shop_id])->delete()){
                $this->success(__('删除成功',[]));
            }else{
                $this->error(__('删除失败'));
            }
        } else {
            $this->error(__('非法请求'));
        }
    }
   
}
